import React, { useState, useEffect } from 'react';
import Taro, { navigateTo, createSelectorQuery, login, scanCode, setStorageSync, getStorageSync, useDidShow, getSetting, openSetting, requestSubscribeMessage, showModal } from '@tarojs/taro';
import CProvider from '@/components/CProvider';
import { View, Text, Image } from '@tarojs/components';
import { IconFont } from '@nutui/icons-react-taro';
import { Scan, Plus, Link, Unlink } from '@nutui/icons-react-taro'
import { Button, ActionSheet, Avatar, Input, Dialog, Toast, Badge, Popup, PullToRefresh } from '@nutui/nutui-react-taro'
import './home.less';
import { useDebounceEffect, useRequest } from 'ahooks';
import doFetch from '@/utils/doFetch';
import { getToken, setToken } from '@/utils/auth'
import dayjs from 'dayjs';

const options = [
  {
    name: '扫码绑定',
  },
  {
    name: '输入编码绑定',
  },
]

const ids = ['zlkNl2q6LiDjnZ2OsGEvFUirRPPnIvUxVd2gc5qPevE', 'XbpLyym7oCNZixY9GMnu_WyxJrbR9012kC9igO38IvQ'];

export default function Home() {
  const [showBasic, setShowBasic] = useState(false); //获取用户信息授权

  const [isVisible, setIsVisible] = useState(false);
  const [open, setOpen] = useState(false);
  const [devicecode, setDeviceCode] = useState(null);
  const [errormsg, setErrorMsg] = useState();
  const [showToast, setShowToast] = useState(false);
  const [state, setState] = useState({
    avatarUrl: getStorageSync('avatarUrl'),
    nickname: getStorageSync('nickname'),
  });

  const { data, run, refreshAsync } = useRequest(async () => {
    let res = await doFetch({ url: "/mini/device_mini", params: {}, method: "GET" })
    return res?.data?.data?.dataList
  }, {
    manual: true
  })


  useDidShow(() => {
    if (getToken()) {
      run()
      return
    }
  })

  function applyMessage(ids) {
    return new Promise((resolve, reject) => {
      if (!requestSubscribeMessage) {
        resolve();
        return;
      }
      // 弹窗通知提醒
      requestSubscribeMessage({
        tmplIds: ids,
        success: (res) => {
          if (ids?.some(id => res[id] === 'accept')) {
            setIsVisible(true)
          } else {
            showModal({
              content: '未授权发送通知，请到小程序设置界面开启订阅',
              confirmText: '重新授权',
              cancelText: '取消授权',
              success: (re) => {
                if (re.confirm) {
                  reject();
                  openSetting();
                } else {
                  resolve();
                }
              }
            });
          }
        },
        fail: (err) => {
          showModal({
            content: '未授权发送通知，请到小程序设置界面开启订阅',
            confirmText: '去开启',
            cancelText: '暂不开启',
            success: (res) => {
              if (res.confirm) {
                reject();
                openSetting();
              } else {
                resolve();
              }
            }
          });
        }
      });
      // #endif
      resolve();
    });
  }


  useEffect(() => {
    if (!state.avatarUrl || !state.nickname) {
      setShowBasic(true);
    }
    if (getToken()) {
      return
    }
    login({
      success: async (res) => {
        if (res.code) {
          //发起网络请求
          let result = await doFetch({ url: "/mini/login", params: { code: res?.code }, method: "GET" });
          setToken(result?.data?.data?.openid)
          run()
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      }
    })
  }, []);




  const handleSelect = (item) => {
    switch (item.name) {
      case '扫码绑定':
        scanCode({
          success: async (res) => {
            const devicecode = res.result;
            const wait = await doFetch({ url: "/mini/device_mini", params: { code: devicecode } });
            if (wait?.data?.code === 0) {
              run();
            } else {
              setErrorMsg(wait?.data?.message);
              setShowToast(true)
            }
          }
        })
        setIsVisible(false);
        break;

      case '输入编码绑定':
        setOpen(true);
        setIsVisible(false);
        break;
      default:
        setIsVisible(false);
        break;
    }
  }


  useDebounceEffect(() => {
    if (!state.avatarUrl && !state.nickname) {
      return
    }
    doFetch({
      url: "/mini/user/update_mini_info", params: {
        nick_name: state.nickname,
        head_image: state.avatarUrl
      }, method: "PUT"
    })
    setStorageSync("avatarUrl", state.avatarUrl)
    setStorageSync("nickname", state.nickname)
  }, [
    state
  ], {
    wait: 2000
  })



  return (
    <CProvider>
      <View className="container">
        <Popup
          visible={showBasic}
          position="bottom"
          lockScroll
          onClose={() => {
            setShowBasic(false)
          }}
        >
          <View style={{ height: '200px', padding: "30px 30px 75px 30px", display: "flex", flexDirection: "column", gap: 24 }}>
            <Text style={{ fontSize: '16px', fontWeight: 'bold' }}>请完善您的头像/昵称</Text>
            <div
              className='center' style={{ flex: 1 }}>
              <Button
                className='center'
                fill='none'
                style={{
                  width: 96,
                  height: 96,
                  padding: 0,
                }}
                openType="chooseAvatar"
                onChooseAvatar={(e) => {
                  setState(s => ({
                    ...s,
                    avatarUrl: e.detail.avatarUrl
                  }))
                }}>
                <Avatar
                  size={80}
                  src={state?.avatarUrl || "https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132"}
                  style={{ marginTop: 10 }}
                />
              </Button>
            </div>
            <input
              type="nickname"
              id="nickname-input"
              value={state.nickname}
              onBlur={(e) => {
                createSelectorQuery()
                  .select("#nickname-input")
                  .fields({
                    properties: ["value"],
                  })
                  .exec((res) => {
                    const nickname = res[0].value;
                    setState(s => ({
                      ...s,
                      nickname
                    }))
                  });
              }}
              onInput={(e) => {
                setState(s => ({
                  ...s,
                  nickname: e.detail.value
                }))
              }}
              style={{ backgroundColor: "#f9f9f9", borderRadius: 8, padding: 10 }}
              placeholder='请输入您的昵称'></input>
          </View>
        </Popup>


        <Dialog
          className="test-dialog"
          title="输入设备码"
          visible={open}
          onConfirm={async () => {
            const wait = await doFetch({ url: "/mini/device_mini", params: { code: devicecode } });
            if (wait?.data?.code === 0) {
              setOpen(false);
              run();
            } else {
              setErrorMsg(wait?.data?.message)
            }
          }}
          onCancel={() => {
            setOpen(false);
            setErrorMsg(null);
            setDeviceCode(null);
          }}
          style={{
            '--nutui-dialog-close-color': '#FFFFFF',
          }}
        >
          <Input value={devicecode} onFocus={() => {
            setErrorMsg(null);
          }} onChange={setDeviceCode} placeholder='输入设备码' style={{ backgroundColor: "#f0f0f0", margin: "12px 0", borderRadius: 8 }}></Input>
          {
            errormsg &&
            <Text style={{ color: "red", marginTop: 12 }}>{errormsg}</Text>
          }
        </Dialog>

        <Toast
          type="text"
          content={errormsg}
          duration={2}
          visible={showToast}
          onClose={() => {
            setShowToast(false)
            setErrorMsg(null)
          }}
        />

        <ActionSheet
          title="添加设备"
          visible={isVisible}
          options={options}
          onSelect={handleSelect}
          onCancel={() => setIsVisible(false)}
        />
        {/* 标题 */}
        <View className="header">
          <Avatar
            size={24}
            src={require("@/assets/0.png")}
          />
          <Text className="header-title">
            锂电池火灾自动灭火系统
          </Text>
        </View>

        <View className="spread" style={{ padding: "4px 8px 12px 12px" }}>
          <View className="left gap-12" onClick={() => {
            setShowBasic(true)
          }}>
            <Avatar
              size={20}
              src={state?.avatarUrl || "https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132"}
            />
            <Text className="header-title">你好，{state.nickname || "微信用户"}</Text>
          </View>
          <Button
            type='primary'
            fill='none'
            shape="square"
            icon={<Plus width={16} height={16} />}
            onClick={() => {
              getSetting({
                withSubscriptions: true,
                success(res) {
                  if (res.subscriptionsSetting.mainSwitch) { // 用户点击了“总是保持以上，不再询问”
                    const subs = ids?.filter(id => {
                      return res?.subscriptionsSetting?.itemSettings?.[id] !== 'accept';
                    });
                    if (subs.length > 0) {
                      applyMessage(subs);
                    } else {
                      applyMessage(ids);
                    }
                  } else { // 用户没有点击“总是保持以上，不再询问”则每次都会调起订阅消息
                    applyMessage(ids);
                  }
                }
              })

            }}
            style={{ borderRadius: 8, backgroundColor: "#13c2c2", color: "#fff" }}
          >
            添加设备
          </Button>
        </View>



        {/* 设备卡片 */}
        <PullToRefresh
          onRefresh={() => {
            return refreshAsync()
          }}
        >
          <View className="devices-grid">
            {
              data?.map((it, i) => {
                const link = it?.device?.status === 'online'
                return (
                  <Badge color="red" value={it?.device?.alarm_num} top="8" right="16">
                    <View key={i} className="device-card" onClick={() => {
                      navigateTo({ url: `/pages/proteam/proteam?rid=${it?.id}&id=${it?.device_id}&remark=${it?.device?.remark}&name=${it?.device?.name}&link=${link}&leave=${dayjs(it?.device?.last_online_time).format("YYYY/MM/DD HH:mm:ss")}` });
                    }}>
                      <div className="left gap-12" style={{ color: link ? "#000" : "#999" }}>
                        {
                          link ? <Link /> : <Unlink />
                        }
                        <Text className="device-name"> {it?.device?.name}</Text>
                      </div>
                      <Text className='action'>
                        {it?.device?.remark ?? '暂无位置信息'}
                      </Text>
                      <Text className="device-status" style={{ color: link ? "green" : "#6b7280" }}>{link ? `已连接` : `${dayjs(it?.device?.last_online_time).format("YYYY/MM/DD HH:mm:ss")} 离线`}</Text>
                    </View>
                  </Badge>
                )
              })
            }
          </View>
          {
            data?.length === 0 && <View className='columns'>
              <img
                src={require("@/assets/empty.png")}
                alt=""
              />
              <Text>
                暂无设备 , <Text style={{ fontWeight: "bold", color: "#13c2c2" }} onClick={() => {
                  setIsVisible(true)
                }}>立即添加</Text>
              </Text>
            </View>
          }
        </PullToRefresh>


      </View>

    </CProvider>
  );
}
